package top.chatgqt.SmartChargeStation.demo.netty.utils;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import top.chatgqt.SmartChargeStation.demo.netty.handlers.ImoocClientProtobufHandler;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ConnectUtil {

    private NioEventLoopGroup workerGroup;


    public void connect(String host, int port) {

        // 处理网络IO
        workerGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                // 配置NioEventLoop组件
                .group(workerGroup)
                // 配置Channel组件
                .channel(NioSocketChannel.class)
                // 将ChannelHandler添加到ChannelInitializer
                .handler(new ChannelInitializer<>() {
                    // Channel初始化
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        //  获取 ChannelPipeline
                        ChannelPipeline pipeline = channel.pipeline();

                        pipeline
                                .addLast(new ProtobufVarint32LengthFieldPrepender())
                                .addLast(new ProtobufEncoder())
                                .addLast(new ImoocClientProtobufHandler());
                    }
                });

        doConnect(bootstrap, host, port);
    }

    private void doConnect(Bootstrap bootstrap, String host, int port) {
        ChannelFuture future = null;
        try {
            log.info(">>>> Netty 客户端正在启动");
            future = bootstrap.connect(host, port).sync();

            // 注册监听器
            // 启动时 监听是否连接成功，不成功不断重试
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        log.info(">>>> Netty 客户端连接成功");
                    } else {
                        log.info(">>>> Netty 客户端和服务端断开连接");
                        // 如果连接不上，单独启动一条线程重新连接
                        final EventLoop loop = channelFuture.channel().eventLoop();
                        loop.schedule(new Runnable() {
                            @Override
                            public void run() {
                                doConnect(bootstrap, host, port);
                            }
                        }, 10, TimeUnit.SECONDS);
                    }
                }
            });

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            destroy(future);
        }
    }

    private void destroy(ChannelFuture future) {
        try {
            workerGroup.shutdownGracefully().sync();
            // 关闭通道（若已绑定成功）
            if (future != null && future.channel().isOpen()) {
                future.channel().close().sync();
            }
            log.info(">>>>  Netty 客户端资源已释放");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
